package com.yin.login.web;

import com.yin.login.LoginProperties;
import com.yin.login.biz.AuthBiz;
import com.yin.login.biz.BizException;
import com.yin.login.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("auth")
public class LoginAction {

    @Autowired
    LoginProperties loginProperties;

    @RequestMapping("props")
    public LoginProperties getLoginProperties() {
        return loginProperties;
    }

    @Autowired
    AuthBiz  authBiz;

    @RequestMapping("login")
    Object login(String username, String password,
                 HttpSession session) throws BizException{
        try{
            Object ret = authBiz.login(username, password);
            // 登录成功, 保存用户对象到会话
            session.setAttribute(loginProperties.getSessionKey(),
                    ret);
            return Map.of("msg","登录成功",
                    "code", 1,
                    "data", ret);
        }catch (BizException e){
            return Map.of("msg",e.getMessage(),
                    "code", 0);
        }
    }

    @RequestMapping("myinfo")
    public Object myinfo(HttpSession session){
        Object ret = session.getAttribute(loginProperties.getSessionKey());
        if(ret == null){
            return Map.of("msg","未登录",
                    "code", 0);
        }
        return Map.of("msg","查询成功",
                "code", 1,
                "data", ret);
    }

    @RequestMapping("logout")
    public Object logout(HttpSession session){
        session.invalidate();
        return Map.of("msg","退出成功",
                "code", 1);
    }

    @RequestMapping("forgetPwd")
    public Object forgetPwd(String username,HttpSession session){
        try {
            String code = authBiz.forgetPwd(username);
            session.setAttribute("forgetVcode",code);
            session.setAttribute("forgetUsername",username);
            return Map.of("msg","发送成功",
                    "code", 1 );
        } catch (BizException e) {
            return Map.of("msg",e.getMessage(),
                    "code", 0);
        }
    }

    @RequestMapping("resetPwd")
    public Object resetPwd(String pwd, String repwd,
                           String vcode,HttpSession session){
        try{
            String username = (String) session.getAttribute("forgetUsername");
            String scode = (String) session.getAttribute("forgetVcode");
            Utils.checkEmpty(vcode, "验证码不能为空")
                    .check(!scode.equals(vcode), "验证码错误");
            authBiz.resetPwd(username, pwd, repwd);
            return Map.of("msg","密码重置成功",
                    "code", 1);
        } catch (BizException e){
            return Map.of("msg",e.getMessage(),
                    "code", 0);
        }
    }
}
